//
//  AddDiaryViewModel.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/3/5.
//

import Foundation
import SwiftUI
class AddDiaryViewModel : BaseViewModel {
    var delPicture : [CloudPictureBean] = [] //删除图片
    
    func doSave(bean: DiaryBean,mediaItems: [MediaItem],sucResult: @escaping ()-> Void) {
        request {
            self.updateLetterNum(bean)//更新首字母
            bean.mood = MoodExt.getMood(content: bean.content ?? "") //更新表情
            //删除图片跟音频
            try await self.deleteImg()
            self.deleteSound()
            //上传声音要在日记前面，因为没有做单独的表
            //            uploadSound(diaryBean.sound)
            try await BackupsManager.shared.getDelegateDiary()?.saveDiary(bean: bean)
            let listPicture = try await self.uploadImg(bean.objectId ?? "", mediaItems)
            try await self.uploadDiaryPicture(diaryBean: bean, list: listPicture)
            return ""
        } suc: { _ in
            sucResult()
        } fail: {
            showToast($0.message)
        }
    }
    
    func delete(bean: DiaryBean , sucResult: @escaping ()-> Void) {
        request {
            self.delPicture.removeAll()
            bean.listDiaryPicture?.forEach {
                self.delPicture.append($0)
            }
            //删除图片跟音频
            try await self.deleteImg()
            self.deleteSound()
            
            try await BackupsManager.shared.getDelegateDiary()?.delDiary(bean: bean)
            return ""
        } suc: { _ in
            sucResult()
        } fail: {
            showToast($0.message)
        }
    }
    
    
    // 更新首字母
    func updateLetterNum(_ bean: DiaryBean)  {
        let string = bean.content ?? ""
        let letterNum = getPinyinInitials(string)
        // 如果 title 的拼音首字母为空，则尝试从 content 中获取
        if !letterNum.isEmpty {
            let length = min(string.count, 5)
            let substring = String(string.prefix(length))
            let letterNum = getPinyinInitials(substring)
            bean.letterNum = letterNum
        }
    }
    
    func deleteImg() async throws {
        for index in (0..<delPicture.count).reversed() {
            let item = delPicture[index]
            //删除图片
            try await BackupsManager.shared.getDelegateConfig()?.delUrl(fileId: item.fileId ?? "")
            //删除数据库
            try await BackupsManager.shared.getDelegateDiary()?.delCloudPicture(bean: item)
            delPicture.remove(at: index)
        }
    }
    
    func deleteSound(){}
    
    func uploadImg(_ diaryId:String, _ mediaItems: [MediaItem]) async throws -> [CloudPictureBean] {
        var list : [CloudPictureBean] = []
        for (index,item) in mediaItems.enumerated() {
            var cloudPictureBean : CloudPictureBean
            switch item.type {
            case .localImage(let uiImage):
                let key = "\(userManager.getUserId())_\(UUID())\(index)"
                let bean = try await BackupsManager.shared.getDelegateConfig()?.upload(image: uiImage, name: key)
                if bean == nil {
                    continue
                }
                cloudPictureBean = bean!
            case .localVideo(let url):
                let key = "\(userManager.getUserId())_\(UUID())\(index)"
                let bean = try await BackupsManager.shared.getDelegateConfig()?.upload(url: url, name: key)
                if bean == nil {
                    continue
                }
                cloudPictureBean = bean!
            case .networkImage(_, _, _):
                continue
            case .localImagePath(_):
                continue
            }
            cloudPictureBean.folderId = try await BackupsManager.shared.getDelegateConfig()?.getFolderConfig().dbFolderMainId
            cloudPictureBean.userId = userManager.getUserId()
            cloudPictureBean.diaryId = diaryId
            list.append(cloudPictureBean)
        }
        
        return list
    }
    
    func uploadDiaryPicture(diaryBean: DiaryBean,list : [CloudPictureBean]) async throws {
        if !list.isEmpty {
            //图片不为空，则要判断是否有主目录，没有则需要创建,直接传空的过去，统一在代理那边做出来
            try await retry(maxRetries: 10, retryDelayMillis: 500) {
                try await BackupsManager.shared.getDelegateConfig()?.createMainFolderDB(folder: nil)
            }
        }
        for (index, item) in list.enumerated() {
            item.time = diaryBean.time//设置为日期的时间
            item.sort = index
            try await retry(maxRetries: 10, retryDelayMillis: 500){
                try await BackupsManager.shared.getDelegateDiary()?.saveCloudPicture(bean: item)
            }
            
        }
    }
    
    func setAiRule(bean: Binding<DiaryBean>, list: [AiReplyBean]?) {
        request {
            if bean.wrappedValue.aiRule == nil {
                bean.wrappedValue.aiRule = AiRuleBean()
            }
            if ((list ?? []).isEmpty) {
                //随机几个出来
                var listSelect : [AiRoleBean] = Array(try await BackupsManager.shared.getDelegateConfig()?.getSelectAiRoleList().prefix(5) ?? [])
                //是否执行随机
                if AppStorageManager.shared.isRandomMultipleToggle && Bool.random() {
                    listSelect = listSelect.getRandomSubList()
                }
                bean.wrappedValue.aiRule?.listAiRole = listSelect.map { AiReplyBean(roleId: $0.objectId)}.shuffled()
            } else {
                bean.wrappedValue.aiRule?.listAiRole = list?.shuffled()
            }
            return ""
        } suc: { _ in
            
        } fail: {
            showToast($0.message)
        }
    }
    
}
